#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-aliases
# REQUIRE: FILESYSTEMS
# BEFORE: mountlate

. /etc/rc.subr

generate_aliases()
{
	local IFS="|"
	local f="bsdusr_username bsdusr_email"
	eval local $f
	local sf=$(var_to_sf $f)
	local user email
	cp /conf/base/etc/aliases /etc/aliases
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT
	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT $sf FROM account_bsdusers WHERE bsdusr_email != ''" | \
	while eval read $f; do
		if grep -q "^${bsdusr_username}" /etc/aliases; then
			sed -i '' -E "s/^${bsdusr_username}:.*/${bsdusr_username}: ${bsdusr_email}/" /etc/aliases
        	else
			echo "${bsdusr_username}: ${bsdusr_email}" >> /etc/aliases
		fi
	done
}

name="ix-aliases"
start_cmd='generate_aliases'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
